<template>
  <div class="outer-container">
    <div class="container">
      <div class="login-container">
        <div class="header">
          <div class="icon-box">
            <div class="pulse"></div>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              class="beat"
            >
              <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
              <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
              <circle cx="12" cy="8" r="2"></circle>
              <path d="M12 16v-3"></path>
            </svg>
          </div>
        </div>
        <h1>找回密码</h1>
        <p class="subtitle">心理健康管理系统平台</p>

        <!-- 验证账号步骤 -->
        <div v-if="currentStep === 1">
          <el-form
            :model="verifyForm"
            :rules="verifyRules"
            ref="verifyFormRef"
            @submit.prevent="verifyAccount"
          >
            <el-form-item prop="accountId">
              <el-input
                v-model="verifyForm.accountId"
                placeholder="请输入账号"
                :prefix-icon="User"
                clearable
                class="rounded-input"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                class="btn-login"
                native-type="submit"
                :loading="loading"
                round
              >
                {{ loading ? '验证中...' : '验证账号' }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 重置密码步骤 -->
        <div v-if="currentStep === 2">
          <el-form
            :model="resetForm"
            :rules="resetRules"
            ref="resetFormRef"
            @submit.prevent="resetPassword"
          >
            <el-form-item prop="password">
              <el-input
                v-model="resetForm.password"
                placeholder="请输入新密码"
                :type="passwordVisible ? 'text' : 'password'"
                :prefix-icon="Lock"
                class="rounded-input"
              >
                <template #suffix>
                  <span
                    v-if="resetForm.password"
                    class="custom-password-toggle"
                    @mousedown.prevent="togglePasswordVisibility"
                  >
                    <el-icon>
                      <component :is="passwordVisible ? View : Hide" />
                    </el-icon>
                  </span>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input
                v-model="resetForm.confirmPassword"
                placeholder="请确认新密码"
                :type="confirmPasswordVisible ? 'text' : 'password'"
                :prefix-icon="Lock"
                class="rounded-input"
              >
                <template #suffix>
                  <span
                    v-if="resetForm.confirmPassword"
                    class="custom-password-toggle"
                    @mousedown.prevent="toggleConfirmPasswordVisibility"
                  >
                    <el-icon>
                      <component :is="confirmPasswordVisible ? View : Hide" />
                    </el-icon>
                  </span>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                class="btn-login"
                native-type="submit"
                :loading="loading"
                round
              >
                {{ loading ? '提交中...' : '确认修改密码' }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="bottom-options">
          <div>记起密码？<el-link type="primary" @click="toLogin">返回登录</el-link></div>
          <div>没有账号？<el-link type="primary" @click="toRegister">立即注册</el-link></div>
        </div>
        <div class="copyright">
          版权所有 © {{ new Date().getFullYear() }} 心理健康管理系统 - 保留所有权利
        </div>
      </div>
      <div class="decoration-container">
        <img
          src=""
          class="illustration"
          alt="Psychology Illustration"
        />
        <div class="motto">
          <h3>
            {{ currentStep === 1 ? '安心找回，便捷使用' : '设置新密码，重新开始' }}
          </h3>
          <p>
            {{
              currentStep === 1
                ? '请输入您的账号，我们将验证您的身份'
                : '请设置一个新的密码来保护您的账号安全'
            }}
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, View, Hide } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { getByAccountId, recoverPassword } from '@/api/user'

const router = useRouter()
const loading = ref(false)
const currentStep = ref(1)
const userId = ref('')
const verifyFormRef = ref<FormInstance>()
const resetFormRef = ref<FormInstance>()
const passwordVisible = ref(false)
const confirmPasswordVisible = ref(false)

interface VerifyForm {
  accountId: string
}

interface ResetForm {
  password: string
  confirmPassword: string
}

// 验证账号表单
const verifyForm = reactive<VerifyForm>({
  accountId: '',
})

// 重置密码表单
const resetForm = reactive<ResetForm>({
  password: '',
  confirmPassword: '',
})

// 验证账号规则
const verifyRules = reactive<FormRules>({
  accountId: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 5, max: 12, message: '账号长度在5到12位之间', trigger: 'blur' },
  ],
})

// 密码验证规则
const validatePassword = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入新密码'))
  } else if (value.length < 6) {
    callback(new Error('密码不能小于6位'))
  } else {
    callback()
  }
}

// 确认密码验证规则
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请确认新密码'))
  } else if (value !== resetForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 重置密码规则
const resetRules = reactive<FormRules>({
  password: [{ validator: validatePassword, trigger: 'blur' }],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }],
})

// 切换密码可见性
const togglePasswordVisibility = () => {
  passwordVisible.value = !passwordVisible.value
}

// 切换确认密码可见性
const toggleConfirmPasswordVisibility = () => {
  confirmPasswordVisible.value = !confirmPasswordVisible.value
}

// 验证账号
const verifyAccount = async () => {
  if (!verifyFormRef.value) return

  try {
    await verifyFormRef.value.validate()

    loading.value = true

    const response = await getByAccountId(verifyForm.accountId)

    if (response.code === 200 && response.data) {
      userId.value = response.data.id
      currentStep.value = 2
      ElMessage.success('账号验证成功，请设置新密码')
    } else {
      ElMessage.error('账号不存在或验证失败')
    }
  } catch (error: any) {
    console.error('账号验证失败', error)
    if (error.response && error.response.data && error.response.data.msg) {
      ElMessage.error(error.response.data.msg)
    } else {
      ElMessage.error('账号验证失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 重置密码
const resetPassword = async () => {
  if (!resetFormRef.value) return

  try {
    await resetFormRef.value.validate()

    loading.value = true

    const response = await recoverPassword({
      id: userId.value,
      password: resetForm.password,
    })

    if (response.code === 200) {
      ElMessage.success('密码修改成功')
      router.push('/login')
    } else {
      ElMessage.error(response.msg || '密码修改失败，请重试')
    }
  } catch (error: any) {
    console.error('密码重置失败', error)
    if (error.response && error.response.data && error.response.data.msg) {
      ElMessage.error(error.response.data.msg)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('密码重置失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 导航到登录页
const toLogin = () => {
  router.push('/login')
}

// 导航到注册页
const toRegister = () => {
  router.push('/register')
}

// 检查URL参数，如果有账号直接填入
onMounted(() => {
  const urlParams = new URLSearchParams(window.location.search)
  const accountId = urlParams.get('accountId')
  if (accountId) {
    verifyForm.accountId = accountId
  }
})
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', sans-serif;
}

.outer-container {
  min-height: 100vh;
  background: #4086f4;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.container {
  width: 90%;
  max-width: 1100px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  position: relative;
  margin: 0 auto;
  display: flex;
  flex-direction: row-reverse;
}

.login-container {
  width: 480px;
  padding: 60px;
  position: relative;
  z-index: 1;
  background: #fff;
  display: flex;
  flex-direction: column;
}

.decoration-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(45deg, #ebf3ff 0%, #ffffff 100%);
  position: relative;
  overflow: hidden;
  min-height: 500px;
}

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 60px;
}

.icon-box {
  width: 64px;
  height: 64px;
  background-color: #f6f9ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.icon-box svg {
  width: 32px;
  height: 32px;
  color: #4086f4;
}

.pulse {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: rgba(64, 134, 244, 0.1);
  transform: scale(1);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(0.95);
    opacity: 0.7;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.3;
  }
  100% {
    transform: scale(0.95);
    opacity: 0.7;
  }
}

@keyframes beat {
  0% {
    transform: scale(1);
  }
  15% {
    transform: scale(1.15);
  }
  30% {
    transform: scale(1);
  }
  45% {
    transform: scale(1.15);
  }
  60% {
    transform: scale(1);
  }
  100% {
    transform: scale(1);
  }
}

.beat {
  animation: beat 2s infinite;
  transform-origin: center;
}

h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 600;
  text-align: center;
}

.subtitle {
  color: #666;
  font-size: 16px;
  margin-bottom: 40px;
  text-align: center;
}

/* 圆角输入框样式 */
.rounded-input :deep(.el-input__wrapper) {
  border-radius: 20px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.rounded-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #4086f4 inset;
}

.custom-password-toggle {
  cursor: pointer;
  color: #909399;
}

.custom-password-toggle:hover {
  color: #409eff;
}

.btn-login {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  margin-top: 10px;
  border-radius: 20px;
}

.bottom-options {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;
  font-size: 14px;
  color: #666;
}

.copyright {
  text-align: center;
  margin-top: 32px;
  font-size: 12px;
  color: #999;
}

.illustration {
  width: 80%;
  max-width: 300px;
  margin-bottom: 20px;
}

.motto {
  margin-top: 20px;
  text-align: center;
  padding: 0 30px;
}

.motto h3 {
  color: #4086f4;
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 8px;
}

.motto p {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
}

/* Element Plus表单样式调整 */
:deep(.el-form) {
  display: flex;
  flex-direction: column;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__content) {
  display: block;
}

@media (max-width: 900px) {
  .container {
    flex-direction: column;
  }

  .login-container {
    width: 100%;
    order: 2;
  }

  .decoration-container {
    order: 1;
    min-height: 200px;
  }
}

@media (max-width: 600px) {
  .login-container {
    padding: 30px;
  }

  .icon-box {
    width: 50px;
    height: 50px;
  }

  .icon-box svg {
    width: 24px;
    height: 24px;
  }

  h1 {
    font-size: 24px;
  }

  .subtitle {
    font-size: 14px;
  }

  .btn-login {
    height: 44px;
    font-size: 14px;
  }

  .bottom-options {
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
}
</style>
